/**
 * @brief Abstract FreeBSD kqueue.
 *        IEventHandler will provide the method to get the available bytes in the socket\n
 *        receiving buffer and the available space size of socket sending buffer. 
 *        The KQUEUE reactor should use the method; but EPOLL/SELECT(only support Win32)
 *        can not use it.
 *
 * @author Huang RuiGuang
 * @date 2010/01/28
 *
 * Herm socket's reactor library
 * Copyright (c) 2008 by Huang RuiGuang(daemon.huang@gmail.com)
 *
 * Permission to use, copy, modify, distribute and sell this software.
 */

#ifndef HERM_SOCKET_KQUEUE_MULTIPLEXOR_IMPL_H
#define HERM_SOCKET_KQUEUE_MULTIPLEXOR_IMPL_H

#include <memory>
#include "socket_def.h"
#include "herm/base/socket/event_handler.h"

namespace Herm{

class Multiplexor
{
public:
	Multiplexor(int size, int timeout = -1, bool lt = true);
	~Multiplexor();

	void Run();
	void Register(IEventHandler* eh, MultiplexorMask mask);
	void Remove(IEventHandler* eh);
	void EnableMask(IEventHandler* eh, MultiplexorMask mask);
	void DisableMask(IEventHandler* eh, MultiplexorMask mask);
private:
	inline bool OperateHandler(int op, IEventHandler* eh, MultiplexorMask mask)
	{
		struct kevent kevts[1];
		EV_SET(&kevts[0], eh->GetHandle(), mask, op, 0, 0, eh);

		return kevent(m_kqfd, kevts, 1, NULL, 0, NULL) != -1;
	}

private:
	int m_kqfd;	
	int m_size;
	struct kevent* m_kevts;
	struct timespec* m_timeout;
};
}
#endif 

